#include <avr/io.h>
#include <util/delay.h> 
#include "config.h"
#include "morse.h"
#include "beep.h"
#include "led.h"

/** Beep a number -- NOT actually Morse code */
void beepNum(uint16_t n)
{
	uint16_t k=10;
	uint16_t a=0;
	uint16_t b=n;
	uint8_t i;

	do {
		a = b/k;
		b -= a*k;
		k /= 10;
		if (a == 0) {
			dah(); space(); space();
		} else {
			for (i = 0; i < a; i++) {
				dit(); space(); space();
			}
		}
		for (i = 0; i < 10; i++) {
			space();
		}
	} while (k >= 1);
}


/** Beep morse code "SOS" */
void sos()
{
	s(); o(); s();
}

/** Beep morse "K" -.- */
void k()
{
	dah(); dit(); dah(); space();
}

/** Beep morse "O" --- */
void o()
{
	dah(); dah(); dah(); space();
}

/** Beep morse "S" ... */
void s()
{
	dit(); dit(); dit(); space();
}

/** Beep morse "W" .-- */
void w()
{
	dit(); dah(); dah(); space();
}


/** Beep morse number */
/*
void num(int n)
{
	uint16_t dd = 0x3c1f; // %11110000011111
	uint8_t i;

	// 0 -----
	// 1 .----
	// 2 ..---
	// 3 ...--
	// 4 ....-
	// 5 .....
	// 6 -....
	// 7 --...
	// 8 ---..
	// 9 ----.

	for (i=0; i < 5; i++) {
		if (dd & _BV(4+n-i))
			dah();
		else
			dit();
	}
	
}
*/

/** Space between characters = 2 x . */
void space()
{
	_delay_ms(DOT*2); // because we've already delayed 1x
}

/** Morse code dit (.) */
void dit()
{
#ifdef DEBUG 
	ledOn();
#endif
	beepOn();
	_delay_ms(DOT);
#ifdef DEBUG 
	ledOff();
#endif
	beepOff();
	_delay_ms(DOT);
}

/** Morse code dah (-) */
void dah()
{
#ifdef DEBUG 
	ledOn();
#endif
	beepOn();
	_delay_ms(DOT*3);
#ifdef DEBUG 
	ledOff();
#endif
	beepOff();
	_delay_ms(DOT);
}

